<template>
  <div>
    <contact-summary-solt :loading="loading"  ref="businessSummary">
      <template slot="customerSlot" v-if="$store.state.business.transCache.summaryLoaded">
        <backBtn type="business"></backBtn>
        <customer-slot
          :customer="customer"
          :custType="custType"
          :currentBusinessObj="currentBusinessObj"
          @requestUpdateCustInfo="handleRequestUpdateCustInfo"
        >
          <template #noCustomer>
            <span @click="associatedCustomers" class="associatedCustomers">
              <i class="iconfont icon-tianjia-yuan-xian1"></i>
              <span v-if="customer">变更客户</span>
              <span v-else>关联客户</span>
            </span>
          </template>
        </customer-slot>
      </template>
      <template slot="funTabSlot" v-if="$store.state.business.transCache.summaryLoaded">
        <fun-tab-slot model="business" :tabs="tabs" :activeName="refresh" @changeDetailTab="refreshContent" @handleEditTab="handleEditTab" :urlsStres="urlsStr" :isShowToolbar="true" @businessScroll="businessScroll">
          <template slot="businessTab">
            <business v-if="!loading" :cid="cId" :busId="busId" :typeObj="currentBusinessObj" :showHistory="true" @event="businessEvent" :fixed="fixed"></business>
          </template>
          <template slot="contactPlanTab">
            <contact-plan v-if="!loading" :cid="cId" :refresh="refresh" :refreshBusRight="refreshBusRight"></contact-plan>
          </template>
          <template slot="historyTab">
            <contact-history v-if="!loading" :cid="cId" :refresh="refresh" ></contact-history>
          </template>
          <template slot="changeLogTab">
            <operation-log v-if="!loading" :cid="cId" :refresh="refresh" :refreshBusRight="refreshBusRight"></operation-log>
          </template>
          <!--refresh.indexOf('item') > -1 当前的activeName是iframe才进行加载-->
          <template v-if="refresh.indexOf('-') > -1 || tabCount > 1" v-for= "(item, index) in tabUrls" :slot="item._id">
            <div :class="item.businesses && item.businesses.length > 0 ? 'moreIframe-wrap' : 'iframe-wrap'" :key="index">
              <div v-if="item.businesses && item.businesses.length > 0" class="moreIframe-wrap">
                <div clss="businessesSelect" style="margin: 10px">业务类型</div>
                <el-select v-model="toolBarValue" filterable placeholder="请选择" style="margin: 0px 10px 10px">
                  <el-option
                    v-for="(toolBarItem, index) in item.businesses"
                    :key="index"
                    :label="toolBarItem.name"
                    :value="toolBarItem.url">
                  </el-option>
                </el-select>
                <iframe v-if="toolBarValue !== ''" :src="newUrl(toolBarValue)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
              </div>
              <iframe v-else :src="newUrl(item.url, item.isEncode)" frameborder="0" scrolling="auto" class="iframe-con"></iframe>
            </div>
          </template>
        </fun-tab-slot>
        <editTab :tabs="toolTabs" :type="'business'" ref="editBusinessTab" @updateTabConfig="updateTabConfig"></editTab>
      </template>
    </contact-summary-solt>
    <el-dialog class="customer-dialog" :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="customerInfo.title"  :visible.sync="customerInfo.show" v-if="customerInfo.show">
      <add-customer
        :isTag="false"
        :isBlight = "false"
        :labelValue = "customerInfo.labelValue"
        :labelTitle = "customerInfo.title"
        :reSize = "true"
        :isDalog = "customerInfo.isdealog"
        :isDailog = "true"
        :currentBusinessObj="currentBusinessObjNew"
        :custInfo="{}"
        :isTitle="true"
        :labelName="{add: $t('business.addNewCustomer'), merge: $t('business.searchCustomer')}"
        @addCustomer="addCustomer"
        @merge="mergeCustomer"
        @closeDialog="closeDialog"
      ></add-customer>
    </el-dialog>
  </div>
</template>
<script>
  import {isHasMenu, deepClone} from '@/utils/m7Utils'
  import ContactSummarySolt from '@/components/public-modules/contact-summary/index.vue'
  import editTab from '@/components/business-modules/webchat/webchat-right/customer-Information/dialog/editTab'
  import CustomerSlot from '@/components/public-modules/contact-summary/CustomerSlot'
  import FunTabSlot from '@/components/public-modules/contact-summary/FunTab'
  import OperationLog from '@/components/public-modules/cust-tab-content/operation-log/'
  import ContactPlan from '@/components/public-modules/cust-tab-content/contact-plan/'
  import ContactHistory from '@/components/public-modules/cust-tab-content/contact-history/'
  import Business from '@/components/public-modules/cust-tab-content/business/'
  import * as globalTypes from 'src/store/mutation-types'
  import backBtn from '@/components/public-modules/side-bar/BackSideBar.vue'
  import AddCustomer from '../customer/AddCustomer'
  export default {
    name: 'BusinessSummary',
    data () {
      return {
        tabsInit: {
          normalTab: [
            {disabled: false, name: 'business', slotName: 'businessTab', labelName: this.$t('public.business')},
            {disabled: true, name: 'plan', slotName: 'contactPlanTab', labelName: this.$t('public.contactPlan')}
          ],
          tabUrl: {disabled: false}
        },
        // tabsInit: {businessShow: {disabled: false}, plan: {disabled: true}, history: {disabled: true}, changeLog: {disabled: true}, tabUrl: {disabled: false}},
        loading: false,
        tabType: 'business_undeal',
        customerObj: '',
        urlsStr: [],
        cId: '',
        busId: '',
        toolBarValue: '',
        refresh: 'business',
        tabUrls: [],
        toolbarTab: [],
        token: '',
        reload: 0,
        noCustomerType: '',
        fixed: '',
        tabCount: 1,
        customerInfo: {
          show: false,
           isdealog: true,
          labelValue: 6,
          title: this.$t('customer.addCustomer')
        },
        // 业务对象
        currentBusinessObjNew: {
          type: 'business',
          tabType: 'new_business'
        },
      }
    },
    computed: {
      tabs () {
        this.tabsInit.normalTab.forEach(item => {
          if (item.name !== 'business') {
            if (this.customerObj) {
              item.disabled = false
            } else {
              item.disabled = true
            }
          }
          if (!item.slotName) {
            item.disabled = false
          }
        })
        return this.tabsInit
      },
      customer () {
        return this.$store.state.business.current.currentCustomer
      },
      custType () {
        return this.$store.state.business.current.currentCustomer ? 'one' : this.noCustomerType
      },
      refreshBusRight () {
        return this.$store.state.business.transCache.refreshBusRight
      },
      currentBusinessObj () {
        let rou = this.$route.path.split('/')
        return {
          type: rou[2],
          tabType: rou[3]
        }
      },
      toolTabs () {
        let toolTabs = []
        let tabs = deepClone(this.tabs.normalTab)
        for (let i in tabs ) {
          toolTabs.push({...tabs[i]})
        }
        return toolTabs
      }
    },
    watch: {
      // 如果路由有变化，会再次执行该方法
      'refreshBusRight': 'fetchData'
    },
    created () {
    },
    methods: {
      isHaveMenu (func) {
        return isHasMenu(func, this.$store.state.session.user)
      },
      businessScroll (fixed) {
        this.fixed = fixed
      },
      updateTabConfig (val) {
        this.$store.dispatch('saveToolbarTabPosition', {module: 'business', tabs: val}).then(res => {
          this.tabsInit.normalTab = val
          this.getTabUrl()
          this.refreshContent(this.tabsInit.normalTab[0].slotName ? this.tabsInit.normalTab[0].name : this.tabsInit.normalTab[0]._id)
        })
      },
      refreshContent (name) {
        this.refresh = name
        if (name.indexOf('-') > -1) {
          this.tabCount += 1
        }
      },
      handleEditTab () {
        this.$refs.editBusinessTab.open()
      },
      businessEvent (eventData, type) {
//        let event = eventData.event
        let data = eventData.data
        this.busId = data._id
        if (this.$route.path.split('/')[3] === 'business_all') {
          let data2 = {
            _id: this.busId
          }
          this.$store.dispatch('getBusinessDetailById', data2)
          this.$store.commit('business/REFRESH_LEFT', Math.random())
        } else {
          this.$store.commit('business/REFRESH_LEFT', Math.random())
          if (!type) {
            this.$router.push({ path: '/index/business' })
          }
        }
        this.$store.commit('business/SET_BUSINESS_IS_SHOW_BOX', {isShow: false, isRefresh: true})
        //刷新左侧菜单栏数量统计
        this.$store.commit('business/REFRESH_MENUBAR',Math.random())
      },
      getTabUrl () {
        let tabUrles = this.tabsInit.normalTab
        if (tabUrles && tabUrles.length > 0) { // 有tab对接的数据&&有获取token权限时才会去取token
          this.urlsStr = [] // 解决卡片切换之后不断地往里面push的问题
          if (this.$store.state.session.account.tokenCheck) {
            this.$store.dispatch('getToken').then((token) => {
              this.token = token
              tabUrles.forEach(item => {
                this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
              })
            })
          } else {
            tabUrles.forEach(item => {
              this.urlsStr.push(this.newUrl(item.url ? item.url.replace('http://', '//') : ''))
            })
          }
        }
      },
      fetchData () {
        this.loading = true
        this.refresh = this.tabsInit.normalTab[0].slotName ? this.tabsInit.normalTab[0].name : this.tabsInit.normalTab[0]._id
        if (this.refresh.indexOf('-') > -1) {
          this.tabCount = 2
        } else {
          this.tabCount = 1
        }
        let path = this.$route.path.split('/')
        let type = path[2]
        if (type !== 'business') {
          return
        }
        let tabType = path[3]
        this.tabType = tabType
        let _id = path[4]
        let customerId = path[5]
        let query = {
          type: type,
          tabType: tabType,
          _id: _id,
          customerId: customerId
        }
        if (customerId === 'no-customer-bus') {
          this.noCustomerType = 'no-customer-bus'
        } else {
          this.noCustomerType = 'business-del'
        }
        let p1 = getBusDetail(this.$store, _id, query)
        let p2 = getCustInfo(this.$store, query)
        let that = this
        return Promise.all([p1, p2]).then(function () {
          that.customerObj = that.$store.state.business.current.currentCustomer
          that.getTabUrl()
          if (that.customerObj) {
            that.cId = that.customerObj._id
          }
          that.busId = _id
          that.reload = Math.random()
          that.loading = false
        })
      },
      handleRequestUpdateCustInfo (done) {
        try {
          var promise = this.fetchData()
          if (!promise) {
            done()
          } else {
            promise.then(() => {
              this.$store.commit(globalTypes.UPDATE_CUSTOMER_INFO, {data: this.customer})
              done()
            })
          }
        } catch (error) {
          done()
        }
      },
      newUrl (url, isEncode) {
        let routes = this.$route.path.split('/')
        if (routes[2] !== 'business' || !routes[4]) {
          // 切换到其他模块或者是没有到详情的页面的时候，不传参（vepower tab对接，切换到别的模块的时候，赋值了一个不全的地址，切换回来即使地址正确，对接方也取不到正确的地址）
          return ''
        }
        let tabType = routes[2]
        let message = 'tabType=' + tabType
        let customer = this.customer || 0
//        let sid = customer.sid + '__' + customer.sourceName
        let diaplayName = this.$store.state.session.user.displayName || ''
        let exten = this.$store.state.session.user.exten || ''
        if (customer) {
          let phone = ''
          let email = ''
          let weixin = ''
          if (customer.phone && customer.phone.length > 0) {
            for (let i = 0; i < customer.phone.length; i++) {
              phone += customer.phone[i].tel + ','
            }
            phone = phone.substr(0, phone.lastIndexOf(','))
          }
          if (customer.email && customer.email.length > 0) {
            for (let i = 0; i < customer.email.length; i++) {
              email += customer.email[i].email + ','
            }
            email = email.substr(0, email.lastIndexOf(','))
          }
          if (customer.weixin && customer.weixin.length > 0) {
            for (let i = 0; i < customer.weixin.length; i++) {
              weixin += customer.weixin[i].num + ','
            }
            weixin = weixin.substr(0, weixin.lastIndexOf(','))
          }
          let name = customer.name ? customer.name : ''
          let status = customer.status ? customer.status : ''
          if (status) {
            status = this.$getCache('custTmpls')[0].status[status]
          }
          let title = customer.title ? customer.title : ''
          let province = customer.province ? customer.province : ''
          let city = customer.city ? customer.city : ''
          let address = customer.address ? customer.address : ''
          let note = customer.note ? customer.note : ''
          let web = customer.web ? customer.web : ''
//          let sex = customer.sex ? customer.sex === '0' ? this.$t('public.male') : this.$t('public.famel') : ''
          let sex = ''
          if (customer.sex) {
            if (customer.sex === '0') {
              sex = this.$t('public.male')
            } else if (customer.sex === '1') {
              sex = this.$t('public.famel')
            }
          }
          let age = customer.age ? customer.age : ''
          let birth = customer.birth ? customer.birth : ''
          if (city && province) {
            let list = {}
            let that = this
            let newOptions = that.$getCache('options')
            for (let ind in newOptions) {
              if (newOptions[ind].accountId === 'system' && newOptions[ind].name === '省市县') {
                list = newOptions[ind].options
                break
              }
            }
            for (let i = 0; i < list.length; i++) {
              if (list[i].key === province) {
                for (let j = 0; j < list[i].options.length; j++) {
                  if ((list[i].options[j]).key === city) {
                    city = list[i].options[j].name
                    break
                  }
                }
                province = list[i].name
                break
              }
            }
          }
          let custTmpls = this.$getCache('custTmpls')
          if (custTmpls && custTmpls.length > 0 && custTmpls[0].template_type !== 'company') {
            message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
              '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
              '&note=' + note + '&sex=' + sex + '&age=' + age + '&birth=' + birth + '&displayName=' + diaplayName + '&exten=' + exten
          } else {
            message = (message ? message + '&' : '') + 'name=' + name + '&status=' + status + '&title=' + title + '&phone=' + phone + '&email=' + email +
              '&weixin=' + weixin + '&province=' + province + '&city=' + city + '&address=' + address +
              '&note=' + note + '&web=' + web + '&displayName=' + diaplayName + '&exten=' + exten
          }
        } else {
          message += '&displayName=' + diaplayName + '&exten=' + exten
        }
        if (url && (url.indexOf('power.7moor.com') > -1 || url.indexOf('power-') > -1)) {
          if (this.$store.state.session.sessionId && window.sessionStorage.getItem('loginToken')) {
            message += '&sessionId=' + this.$store.state.session.sessionId + '&loginToken=' + window.sessionStorage.getItem('loginToken')
          }
        }
        message += '&accountId=' + this.$store.state.session.account.account
        if (this.$store.state.session.account.tokenCheck) {
          if (this.token.token) {
            if (message) {
              message += '&token=' + this.token.token + '&tokenId=' + this.token.tokenId
            } else {
              message = 'token=' + this.token.token + '&tokenId=' + this.token.tokenId
            }
          }
        }
        if (message.indexOf('#') !== -1) {
          message = message.replace(/#/g, '%23')
        }
        let parpmUrl = ''
        if (message && url && url.indexOf('?') === -1) {
          parpmUrl = url + '?' + message
        } else if (message) {
          parpmUrl = url + '&' + message
        } else {
          parpmUrl = url
        }
        if (isEncode) {
          parpmUrl = encodeURI(parpmUrl)
        }
        return parpmUrl.replace('http://', '//').replace('${customerId}', customer ? customer._id : '')
      },
      associatedCustomers() {
        this.customerInfo.show = true
      },
      addCustomer (form) {
        delete form.dealSrc
        delete form.callId
        this.$store.dispatch('addCustomer', form).then((val) => {
          if (val.success) {
            const cData = {
              customer: val.data._id,
              _id: this.busId
            }
            this.$store.dispatch('orderUpdateCustomer', cData).then(res => {
              if (res.success) {
                this.$store.state.business.current.currentCustomer = val.data
                const routeType = this.$route.path.split('/')[3]
                this.$router.push({ path: `/index/business/${routeType}/${this.busId}/${val.data._id}` })
                this.customerInfo.show = false
                const newData = {
                  data: {
                    _id: this.busId
                  }
                }
                this.fetchData()
                this.businessEvent(newData, true)
              }
            })
          }
        })
      },
      // 选择已有客户
      mergeCustomer (data) {
        const cData = {
          customer: data.custInfo._id,
          _id: this.busId
        }
        this.$store.dispatch('orderUpdateCustomer', cData).then(async res => {
          if (res.success) {
            this.$store.state.business.current.currentCustomer = data.custInfo
            this.customerInfo.show = false
            const routeType = this.$route.path.split('/')[3]
            this.$router.push({ path: `/index/business/${routeType}/${this.busId}/${data.custInfo._id}` })
            const newData = {
              data: {
                _id: this.busId
              }
            }
            this.fetchData()
            await this.businessEvent(newData, true)

          }
        })
      },
      closeDialog () {
        this.customerInfo.show = false
      }
    },
    components: {
      ContactSummarySolt,
      CustomerSlot,
      FunTabSlot,
      Business,
      ContactPlan,
      ContactHistory,
      OperationLog,
      editTab,
      backBtn,
      AddCustomer
    },
    beforeMount () {
      this.loading = false
      let p1 =  this.$store.dispatch('queryToolbarTabPosition', {module: 'business'})
      let p2 = this.$store.dispatch('getCache', {type: 'tabUrlAddress'})
      let p3 = this.$store.dispatch('getCache', {type: 'options'})
      Promise.all([p1, p2, p3]).then(([res]) => {
        if (res && res.data) {
          let normalTab = []
          let list = res.data || []
          let toolbarTabArr = []
          for (let i = 0; i < list.length; i++) {
            if ('show' in list[i] && !list[i].show) {
              continue
            }
            if (list[i].businesses || list[i].url) {
              toolbarTabArr.push(list[i])
              if ('editable' in list[i]) {
                normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, type: 'toolbar'})
              } else {
                normalTab.push({_id: list[i]._id, disabled: false, name: list[i].name, url: list[i].url, isEncode: list[i].isEncode})
              }
            } else {
              if (list[i].tabName === 'history') {
                if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_contact_history')) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: 'history', slotName: 'historyTab', labelName: this.$t('public.history')})
                }
              } else if (list[i].tabName === 'changeLog') {
                if ((this.$store.state.session.user && this.$store.state.session.user.isAdmin) || !this.isHaveMenu('func_operation_log')) {
                  if (this.$store.state.session.account.isSouthEastAsia !== 'true') {
                    normalTab.push({_id: list[i]._id, disabled: false, name: 'changeLog', slotName: 'changeLogTab', labelName: this.$t('public.changeLog')})
                  }
                }
              } else if (list[i].tabName === 'contactPlan') {
                normalTab.push({_id: list[i]._id, disabled: false, name: 'plan', slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
              } else {
                if (list[i].tabName) {
                  normalTab.push({_id: list[i]._id, disabled: false, name: list[i].tabName, slotName: list[i].tabName + 'Tab', labelName: this.$t(list[i].name)})
                }
              }
            }
          }
          this.toolbarTab = toolbarTabArr
          this.tabsInit.normalTab = normalTab
        }
        this.tabUrls = this.toolbarTab
        this.$store.commit('business/SUMMATY_LOADED', true)
        this.fetchData()
      })
    }
  }
  function getBusDetail (store, _id, query) {
    let data = {_id: _id}
    return store.dispatch('getBusinessDetailById', data)
  }
  function getCustInfo (store, query) {
    let queryData = {
      _id: query.customerId,
      type: query.type,
      tabType: query.tabType
    }
    return store.dispatch('queryCustomerInfo', queryData)
  }
</script>
<style rel="stylesheet/stylus" lang="stylus" scoped>
.associatedCustomers
  color: #459ae9
  font-size: 14px
  margin-left: 7px
  cursor pointer
</style>
